package com.lagou.test04.test01;

import java.util.ArrayList;
import java.util.List;

public class StudentServiceImpl implements StudentService {

    private List<Student> students= new ArrayList<Student>();
    public StudentServiceImpl() {}

    @Override
    public boolean addStudent(Student student) throws StuNoException {
        //顺序插入，初始客户号为0
        //如果客户号已存在，则不能插入，并提示插入失败
        int stuNo = student.getStuNo();
        //判断客户号是否存在
        for (Student stu:students) {
            if (stuNo == stu.getStuNo()) {
                throw new StuNoException("学号"+stuNo+"已存在，插入失败！");
            }
        }

        boolean flag =  students.add(student);
        queryStudentList();
        return flag;
    }

    @Override
    public boolean delStudent(int stuNo) {
        //通过学号查询学生信息
        Student student = queryStudentInfo(stuNo);
        //移除学生
        boolean flag = students.remove(student);
        queryStudentList();
        return flag;
    }

    @Override
    public boolean updateStudent(Student student) throws StuNoException {
        Student stu = queryStudentInfo(student.getStuNo());
        if (stu != null) {
            students.remove(stu);
            return addStudent(student);
        }
        queryStudentList();
        return false;
    }

    @Override
    public Student queryStudentInfo(int stuNo) {
        Student student = null;
        for (Student stu:students) {
            if (stuNo == stu.getStuNo()) {
                student = stu;
                break;
            }
        }

        return student;
    }

    @Override
    public void queryStudentList() {
        for (Student stu:students) {
            System.out.println(stu.toString());
        }
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}
